//
//  JXOauthViewController.swift
//  swift高仿微博
//
//  Created by peijiaxing on 16/2/25.
//  Copyright © 2016年 peijiaxing. All rights reserved.
//

import UIKit

import SVProgressHUD

class JXOauthViewController: UIViewController,UIWebViewDelegate {

    lazy var webView: UIWebView = UIWebView()
    
    
    override func loadView() {
        
        view = webView
        
        setupNav()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 创建URL
       let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=1767425502&redirect_uri=http://www.itcast.cn&response_type=code")!
        // 创建网络请求
        let  request = NSURLRequest(URL: url)
         // 发型网络请求
        webView.loadRequest(request)
        
        webView.delegate = self
    }

    // 设置NAV
    
    private func setupNav(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
    }
    
    // 返回按钮
    func dismiss(){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    func autofill(){
        let JXString = "document.getElementById('userId').value='295500489@qq.com';document.getElementById('passwd').value='p15124619619'"
        
        webView.stringByEvaluatingJavaScriptFromString(JXString)
    }

}
extension JXOauthViewController{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 去访问网络 并返回一个返回值
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1 判断url 是否有值 （request.URL?.absoluteString 是URL 的绝对路径 能把URL 转化成 string）
        if let urlString = request.URL?.absoluteString{
            //2.url有值的话，再次判断一下url是否是 http://www.itcast.cn开头
            if urlString.hasPrefix(AppRedirectUri){
                 //3.如果是重定向的url，我们需要截获url后边的参数
                let query = request.URL?.query
                //4. 截获url来获得 code
                let code = query!.substringFromIndex("code=".endIndex)
                
               
                JXUserViewModel.shareInstance.loadToken(code, success: { () -> () in
                    print("成功")
                    
                NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEnter, object: nil)
                    
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                    })
                    }, failure: { () -> () in
                        print("失败")
                })
                
            }
            
        }
        return true
    }

}




















